/*
 * @Author: zhangwenbangde@163.com
 * @Date: 2020-09-15 19:31:02
 * @LastEditTime: 2020-09-15 19:34:32
 */

 
import service from '@/utils/axios';

import { Toast } from 'vant'

let fetchCount= 0; // 某小段时间内正在请求的接口数量
const axiosMethod = (_config:any) => {
  if(fetchCount===0){
    Toast.loading({
      message: '加载中...',
      forbidClick: true,
      duration: 0,
    });
  }
  ++fetchCount;
  return service(_config)
    .then(response => {
      if (_config.file) {
        _config.filename = _config.filename
          ? _config.filename
          : ''
          
        return response.data;
          
      }
      return response.data;
    })
    .then(res => {
      setTimeout(() => {
        fetchCount = fetchCount - 1 < 0 ? 0 : fetchCount - 1;
        if (fetchCount === 0) {
          Toast.clear();
        }
      }, 50);
      return res;
    })
    .catch(err => {
      fetchCount = fetchCount - 1;
      if (fetchCount === 0) {
        Toast.clear();
      }
      throw console.log(err);
    });
};

class AxiosApi {
  url:string;
  constructor(_url:string) {
    this.url = _url;
  }

  get(urlSearchParams:any={}, config = {}) {
    Object.assign(config, {
      method: 'get',
      url: this.url,
      params: urlSearchParams
    });
    return axiosMethod(config);
  }

  post(urlSearchParams:any={}, bodyParams:any, config = {}) {
    let _bodyParams=bodyParams;
    Object.assign(config, {
      method: 'post',
      url: this.url,
      data: _bodyParams,
      params: urlSearchParams
    });
    return axiosMethod(config);
  }

  put(urlSearchParams:any={}, bodyParams:any, config = {}) {
    
    Object.assign(config, {
      method: 'put',
      url: this.url,
      data: bodyParams,
      params: urlSearchParams
    });
    return axiosMethod(config);
  }

  patch(urlSearchParams:any={}, bodyParams:any, config = {}) {
    Object.assign(config, {
      method: 'patch',
      url: this.url,
      data: bodyParams,
      params: urlSearchParams
    });
    return axiosMethod(config);
  }
}

const axiosResource = (url:string) => {
  return new AxiosApi(url);
};

export { axiosResource };
